home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 8877 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.3 KB

  1. From: LittleGuyRascal@msn.com (Gregory Saxton)
  2. Subject: RE: Will it be auto-deleted?
  3. Date: 27 Feb 96 03:58:17 -0800
  4. References: <1996Feb20.110314.46035@yogi.urz.unibas.ch>
  5. Message-ID: <00001a81+0000a898@msn.com>
  6. Path: news.msn.com!msn.com
  7. Newsgroups: comp.lang.c++
  8. Organization: The Microsoft Network (msn.com)
  9.  
  10. You are half right.
  11.  
  12. Since mypointer is an automatic variable in function myfunction it 
  13. will be deleted from the stack when the function exits.
  14.  
  15. The array of 100 elements of type double allocated via operator new 
  16. will remain on the heap until that magic moment when someone issues a 
  17. delete [] mypointer;
  18.  
  19. There is a bonus problem here.  Since the value mypointer is lost 
  20. when the function exits you have a memory leak which may exhaust the 
  21. heap depending on the usage of this function.
  22.  
  23. Copy the below statement to a post-it and put it on your monitor! 
  24. -- If I allocate memory via operator new I must delete it - or someone must --
  25.  
  26. Suggestions 
  27.  
  28. - Make the pointer static so the value remains intact during 
  29. subsequent function calls to myfunction - just don't allocated the 
  30. array each time the function is called.
  31.  
  32. - Make the pointer global and allocate the data somewhere else, and 
  33. delete it somewhere else, like in a class constructor and destructor.
  34.  
  35. enjoy...
  36.